<?php

namespace App\Http\Imports\BaseData;

use App\Models\Dic;
use App\Models\MaterialCategory;
use App\Models\Material;
use App\Models\PointStick;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class PointStickImport implements ToCollection
    {
    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
        {
        //编码1	规格2	代号3	花型4	上胶量(g)5	损耗率%6	门幅(米)7	备注8
        set_time_limit(0);
        $collection->filter(function ($v, $k)
            {
            if ($k == 0) {
                return;
                }
            $code           = $v[0];
            $spec           = $v[1];
            $name           = $v[2];
            $flower_pattern = $v[3];
            $has_quantity   = $v[4];
            $loss_rate      = $v[5];
            $width          = $v[6];
            $remark         = $v[7];
            $category       = $v[8];

            $gluecategory = Dic::whereCode("gluecategory")->whereName($category)->first();

            if ($gluecategory) {
                $category_id = $gluecategory->key;
                }
            else {
                fail("{$category}分组不存在！");
                }

            if (isEmpty(trim($width)) || !is_numeric($width) || $width <= 0) {
                fail("门幅不能为空或小于等于0");
                }
            if (isEmpty(trim($has_quantity)) || !is_numeric($has_quantity) || $has_quantity <= 0) {
                fail("上胶量不能为空或小于等于0");
                }
            $use_quantity = $has_quantity * $width / 1000;
            $meter_per_kg = (1000 / $width / $has_quantity) * (1 - $loss_rate / 100);

            PointStick::create([
                'code'           => $code,
                'name'           => $name,
                'spec'           => $spec,
                'flower_pattern' => $flower_pattern,
                'has_quantity'   => $has_quantity,
                'loss_rate'      => $loss_rate,
                'width'          => $width,
                'remark'         => $remark,
                'use_quantity'   => $use_quantity,
                'meter_per_kg'   => $meter_per_kg,
                'category_id'    => $category_id
            ]);
            });

        }
    }
